package com.alinpay.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alinpay.config.AlipayConfig;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Alipay {
    @RequestMapping("/alipay")
    public void pay(String price, String name, HttpServletResponse response) throws Exception {
        DefaultAlipayClient Client =
                new DefaultAlipayClient(AlipayConfig.gatewayUrl,
                        AlipayConfig.app_id,AlipayConfig.merchant_private_key, "json",
                        AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type
                );
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no",System.currentTimeMillis());
        map.put("total_amount",price+".00");
        map.put("subject",name);
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        String ss = JSONObject.toJSONString(map);
        alipayTradePagePayRequest.setBizContent(ss);//把订单数据打包（请求对象）
        String body = Client.pageExecute(alipayTradePagePayRequest).getBody();
        response.setContentType("text/html;charset=utf-8");//确定返回格式
        response.getWriter().write(body);//写到前端页面
        response.getWriter().close();
    }
}
